package com.zscat.mallplus.center.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.center.entity.CenterExtendVO;
import com.zscat.mallplus.center.entity.CenterInviteRecords;
import com.zscat.mallplus.center.entity.CenterUserSysNotice;
import com.zscat.mallplus.center.entity.CenterVerification;
import com.zscat.mallplus.center.mapper.CenterInviteRecordsMapper;
import com.zscat.mallplus.center.mapper.CenterMemberInfoMapper;
import com.zscat.mallplus.center.mapper.CenterUserSysNoticeMapper;
import com.zscat.mallplus.center.mapper.CenterVerificationMapper;
import com.zscat.mallplus.center.service.CenterService;
import com.zscat.mallplus.center.vo.CenterInviteVo;
import com.zscat.mallplus.center.vo.CenterMessageVo;
import com.zscat.mallplus.center.vo.MemberInfoVo;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.cms.entity.CmsSubjectComment;
import com.zscat.mallplus.cms.mapper.CmsSubjectCommentMapper;
import com.zscat.mallplus.cms.service.ICmsSubjectService;
import com.zscat.mallplus.fenxiao.entity.FenxiaoMemberTotal;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItem;
import com.zscat.mallplus.oms.entity.OmsOrderItemTicket;
import com.zscat.mallplus.oms.mapper.OmsOrderItemMapper;
import com.zscat.mallplus.oms.mapper.OmsOrderMapper;
import com.zscat.mallplus.oms.service.IOmsOrderItemTicketService;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.pay.utils.StringUtils;
import com.zscat.mallplus.pay.utils.StringUtils.RandomType;
import com.zscat.mallplus.sys.entity.AdminSysNotice;
import com.zscat.mallplus.sys.mapper.AdminSysNoticeMapper;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.entity.UmsMemberMemberTagRelation;
import com.zscat.mallplus.ums.entity.UmsMemberTag;
import com.zscat.mallplus.ums.mapper.UmsMemberMapper;
import com.zscat.mallplus.ums.mapper.UmsMemberMemberTagRelationMapper;
import com.zscat.mallplus.ums.mapper.UmsMemberTagMapper;
import com.zscat.mallplus.ums.service.IFenxiaoMemberTotalService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.utils.CommonResult;

@Service
public class CenterServiceImpl implements CenterService {
	@Resource
	private CenterMemberInfoMapper memberInfoMapper;
	@Resource
	private CenterInviteRecordsMapper inviteRecordsMapper;
	@Resource
	private AdminSysNoticeMapper adminSysNoticeMapper;
	@Resource
	private CenterUserSysNoticeMapper userSysNoticeMapper;
	@Resource
	private UmsMemberMapper umsMemberMapper;
	@Resource
	private OmsOrderItemMapper omsOrderItemMapper;
	@Resource
	private OmsOrderMapper omsOrderMapper;
	@Resource
	private CenterVerificationMapper verificationMapper;
	@Resource
	private UmsMemberTagMapper memberTagMapper;
	@Resource
	private UmsMemberMemberTagRelationMapper memberTagRelationMapper;
	@Resource
	private CmsSubjectCommentMapper subjectCommentMapper;
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private ICmsSubjectService subjectService;
	@Resource
	private IOmsOrderItemTicketService orderItemTicketService;
	@Resource
	private IOmsOrderService orderService;
	@Autowired
	private IFenxiaoMemberTotalService fenxiaoMemberTotalService;

	@Override
	public CenterInviteRecords getInviteRecordsByInviteId(Long inviteId) {
		return inviteRecordsMapper.getInviteRecordsByInviteId(inviteId);
	}

	@Override
	public int addInviteData(CenterInviteRecords centerInviteRecords) {
		centerInviteRecords.setCreateTime(new Date());
		return inviteRecordsMapper.insertCenterInviteRecords(centerInviteRecords);
	}

	@Override
	public CenterInviteVo getInviteData(Long userId) {
		CenterInviteVo centerInviteVo = new CenterInviteVo();
		List<CenterInviteRecords> inviteRecordsList = inviteRecordsMapper.selectCenterInviteRecordsByUserId(userId);
		centerInviteVo.setCenterInviteRecordsList(inviteRecordsList);
		Long scoreCount = inviteRecordsMapper.countScoreByUserId(userId);
		centerInviteVo.setScoreCount(scoreCount);
		centerInviteVo.setUserCount(inviteRecordsList.size());
		return centerInviteVo;
	}

	@Override
	public MemberInfoVo getMemberInfoData(Long userId) {
		MemberInfoVo memberInfoVo = new MemberInfoVo();
		memberInfoVo.setMember(memberInfoMapper.selectMemberInfoByUserId(userId));
		memberInfoVo.setMemberTagList(memberInfoMapper.selectMemberTagByUserId(userId));
		memberInfoVo.setMemberTagRelationList(new ArrayList<UmsMemberMemberTagRelation>());
		return memberInfoVo;
	}

	@Override
	public List<UmsMemberTag> getMemberTagsData() {
		return memberInfoMapper.selectMemberTags();
	}

	@Override
	public boolean updateMemberInfo(MemberInfoVo memberInfoVo) {
		memberInfoMapper.deleteMemberRelationByUserId(memberInfoVo.getUserId());
		if (memberInfoVo.getMemberTagRelationList() != null && !memberInfoVo.getMemberTagRelationList().isEmpty()) {
			for (UmsMemberMemberTagRelation memberMemberTagRelation : memberInfoVo.getMemberTagRelationList()) {
				memberMemberTagRelation.setMemberId(memberInfoVo.getUserId());
				memberMemberTagRelation.setCreateTime(new Date());
				memberInfoMapper.insertMemberRelation(memberMemberTagRelation);
			}
		}
		if (memberInfoVo.getMember() == null) {
			return true;
		}
		memberInfoVo.getMember().setId(memberInfoVo.getUserId());
		return memberInfoMapper.updateMemberInfo(memberInfoVo.getMember()) > 0 ? true : false;
	}

	@Override
	public int addAdminSysNotice(AdminSysNotice adminSysNotice) {
		CenterUserSysNotice centerUserSysNotice = new CenterUserSysNotice();
		centerUserSysNotice.setIsRead(0);
		centerUserSysNotice.setNoticeId(adminSysNotice.getNoticeId());
		centerUserSysNotice.setStoreId(1L);

		List<UmsMember> umsMemberList = umsMemberMapper.selectList(new QueryWrapper<UmsMember>().eq("status", 1));
		for (UmsMember umsMember : umsMemberList) {
			centerUserSysNotice.setUserId(umsMember.getId());
			userSysNoticeMapper.insertCenterUserSysNotice(centerUserSysNotice);
		}
		return umsMemberList.size();
	}

	@Override
	public CenterMessageVo getMessageData(Long userId) {
		CenterMessageVo centerMessageVo = new CenterMessageVo();
		// 系统消息
		AdminSysNotice adminSysNoticeTmp = new AdminSysNotice();
		adminSysNoticeTmp.setStatus(0);
//		adminSysNoticeTmp.setNoticeType(1);
		AdminSysNotice adminSysNotice = userSysNoticeMapper.selectCenterUserSysNoticeLatest(adminSysNoticeTmp);
		centerMessageVo.setAdminSysNotice(adminSysNotice);
		CenterUserSysNotice centerUserSysNotice = new CenterUserSysNotice();
		centerUserSysNotice.setUserId(userId);
		centerUserSysNotice.setIsRead(0);
		List<CenterUserSysNotice> centerUserSysNoticeList = userSysNoticeMapper
				.selectCenterUserSysNoticeList(centerUserSysNotice);
		centerMessageVo.setAdminSysNoticeCount(centerUserSysNoticeList.size());
		// TODO 服务消息

		// TODO 活动消息
		return centerMessageVo;
	}

	@Override
	public List<CenterUserSysNotice> getAdminSysNoticeList(Long userId) {
//		List<SysNotice> sysNoticeList = sysNoticeMapper.selectList(new QueryWrapper<SysNotice>().orderByDesc("noticeId"));
		List<CenterUserSysNotice> centerUserSysNoticeList = userSysNoticeMapper.getAdminSysNoticeList(userId);
		return centerUserSysNoticeList;
	}

	@Override
	public AdminSysNotice getAdminSysNotice(Long noticeId) {
		AdminSysNotice adminSysNotice = adminSysNoticeMapper
				.selectOne(new QueryWrapper<AdminSysNotice>().eq("notice_id", noticeId));
		return adminSysNotice;
	}

	@Override
	public boolean addVerification(String orderSn) {
		OmsOrder order = omsOrderMapper.selectOne(new QueryWrapper<OmsOrder>().eq("order_sn", orderSn));
		if (order != null) {
			List<OmsOrderItem> orderItemList = omsOrderItemMapper
					.selectList(new QueryWrapper<OmsOrderItem>().eq("order_sn", orderSn));
			if (orderItemList != null && !orderItemList.isEmpty()) {
				for (OmsOrderItem omsOrderItem : orderItemList) {
					if (omsOrderItem.getProductQuantity().compareTo(0) > 0) {
						CenterVerification centerVerification = new CenterVerification();
						centerVerification.setOrderSn(omsOrderItem.getOrderSn());
						centerVerification.setUserId(order.getMemberId());
						centerVerification.setCreateTime(new Date());
						centerVerification.setVerification(0);
						centerVerification.setVerificationCode(StringUtils.random(12, RandomType.INT));
						verificationMapper.insertCenterVerification(centerVerification);
					}
				}
			}
		}
		return true;
	}

	@Override
	public List<CenterVerification> listVerification(CenterVerification verification) {
		return verificationMapper.selectCenterVerificationList(verification);
	}

	@Override
	public boolean scanVerificationCode(CenterVerification verification) {
		verification.setVerification(1);
		verification.setUpdateTime(new Date());
		return verificationMapper.updateCenterVerification(verification) > 0 ? true : false;
	}

	@Override
	public boolean batchScanVerification(List<CenterVerification> verificationList, Integer verificationCount) {
		for (int i = 0; i < verificationCount; i++) {
			CenterVerification centerVerification = verificationList.get(i);
			centerVerification.setUpdateTime(new Date());
			centerVerification.setVerification(1);
			centerVerification.setOperateId(memberService.getNewCurrentMember().getId());
			centerVerification.setOperateName(memberService.getNewCurrentMember().getNickname());
			verificationMapper.updateCenterVerification(centerVerification);
			OmsOrderItemTicket ticket = orderItemTicketService.getOne(
					new QueryWrapper<OmsOrderItemTicket>().eq("coupon_code", centerVerification.getVerificationCode()));
			ticket.setStatus(1);
			orderItemTicketService.updateById(ticket);
		}
		List<OmsOrderItemTicket> list = orderItemTicketService.list(new QueryWrapper<OmsOrderItemTicket>()
				.eq("order_id", verificationList.get(0).getOrderId()).eq("status", 0));
		if (list == null || list.size() == 0) {
			OmsOrder entity = new OmsOrder();
			entity.setId(verificationList.get(0).getOrderId());
			entity.setStatus(3);
			entity.setConfirmStatus(1);
			entity.setReceiveTime(new Date());
			orderService.updateById(entity);
		}
		
		return true;
	}

	@Override
	public List<CenterUserSysNotice> getAdminSysNoticeMemberList(Long noticeId) {
		return userSysNoticeMapper.getAdminSysNoticeMemberList(noticeId);
	}

	@Override
	public List<CenterUserSysNotice> getAllMemberList() {
		return userSysNoticeMapper.getAllMemberList();
	}

	@Override
	public boolean addCenterUserSysNotice(Long[] userIds, Long noticeId) {
		// 删除旧
		userSysNoticeMapper.deleteCenterUserSysNoticeByNoticeId(noticeId);
		for (int i = 0; i < userIds.length; i++) {
			CenterUserSysNotice centerUserSysNotice = new CenterUserSysNotice();
			centerUserSysNotice.setNoticeId(noticeId);
			centerUserSysNotice.setUserId(userIds[i]);
			centerUserSysNotice.setIsRead(0);
			centerUserSysNotice.setCreateTime(new Date());
			userSysNoticeMapper.insertCenterUserSysNotice(centerUserSysNotice);
		}
		return true;
	}

	/**
	 * 保存文章评论
	 *
	 * @param subjectComment
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Object saveSubjectComment(CmsSubjectComment subjectComment) {
		try {
			CmsSubject sub = subjectService.getById(subjectComment.getSubjectId());
			UmsMember currentMember = memberService.getNewCurrentMember();
			if (null != currentMember) {
				subjectComment.setMemberId(currentMember.getId());
				subjectComment.setMemberNickName(currentMember.getNickname());
				subjectComment.setMemberIcon(currentMember.getIcon());
			} else {
				return new CommonResult().failed("请先登录");
			}
			List<CmsSubjectComment> selectList = subjectCommentMapper.selectList(new QueryWrapper<CmsSubjectComment>()
					.eq("subject_id", subjectComment.getSubjectId()).eq("member_id", subjectComment.getMemberId()));
			if (selectList != null && !selectList.isEmpty()) {
				return new CommonResult().failed("用户每个文章仅可评论一次，不可追评");
			}
			subjectComment.setCreateTime(new Date());
			subjectComment.setShowStatus(0);
			subjectComment.setStoreId(sub.getStoreId());
			subjectComment.setStoreName(sub.getStoreName());
			subjectCommentMapper.insert(subjectComment);
			// 根据文章ID查询评论量
			int commentCount = sub.getCommentCount();
			CmsSubject subject = new CmsSubject();
			subject.setCommentCount(commentCount + 1);
			subjectService.update(subject, new QueryWrapper<CmsSubject>().eq("id", subjectComment.getSubjectId()));
			return new CommonResult().success("评论成功");
		} catch (Exception e) {
			return new CommonResult().failed(e.getMessage());
		}
	}

	@Override
	public CenterExtendVO getExtendData(Long userId) {
		CenterExtendVO centerExtendVO = new CenterExtendVO();
		CenterExtendVO orderExtendData = memberInfoMapper.getOrderExtendData(userId);
		CenterExtendVO memberExtendData = memberInfoMapper.getMemberExtendData(userId);
		UmsMember member = memberService.getById(userId);
		FenxiaoMemberTotal fenxiaoMemberTotal = fenxiaoMemberTotalService
				.getOne(new QueryWrapper<FenxiaoMemberTotal>().eq("id", userId));
//		centerExtendVO.setForTheAmount(orderExtendData.getForTheAmount());
		centerExtendVO.setMemberCount(memberExtendData.getMemberCount());
		centerExtendVO.setOrderCount(orderExtendData.getOrderCount());
		centerExtendVO.setTodayAmount(orderExtendData.getTodayAmount());
		centerExtendVO.setTodayMemberCount(memberExtendData.getTodayMemberCount());
		centerExtendVO.setTodayOrderCount(orderExtendData.getTodayOrderCount());
		centerExtendVO
				.setTotalAmount(null == fenxiaoMemberTotal ? BigDecimal.ZERO : fenxiaoMemberTotal.getTotalAmount());
		centerExtendVO
				.setWithdrawAmount(null == fenxiaoMemberTotal ? BigDecimal.ZERO : fenxiaoMemberTotal.getCurrentAmout());
		centerExtendVO.setMember(member);
		return centerExtendVO;
	}
}
